package com.tatesuke.automine.board.mine2k;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

class CellTypeInferencer {

	private static final Map<Integer, Integer> MAP_3_3;
	private static final Map<Integer, Integer> MAP_9_11;
	private static final Map<Integer, Integer> MAP_8_7;
	private static final Map<Integer, Integer> MAP_14_8;
	private static final Map<Integer, Integer> MAP_1_1;
	private static final Map<Integer, Integer> MAP_2_3;

	static {
		MAP_3_3 = new HashMap<Integer, Integer>();
		MAP_3_3.put(0xFF800000, 5);
		MAP_3_3.put(0xFF000000, 7);

		MAP_9_11 = new HashMap<Integer, Integer>();
		MAP_9_11.put(0xFF0000ff, 1);
		MAP_9_11.put(0xFF008000, 2);
		MAP_9_11.put(0xFFff0000, 3);
		MAP_9_11.put(0xFF000080, 4);
		MAP_9_11.put(0xFF008080, 6);
		MAP_9_11.put(0xFF808080, 8);

		MAP_8_7 = new HashMap<Integer, Integer>();
		MAP_8_7.put(0xFFff0000, Mine2KBoard.CELL_TYPE_FLAG);

		MAP_14_8 = new HashMap<Integer, Integer>();
		MAP_14_8.put(0xFFc0c0c0, 0);
		MAP_14_8.put(0xFF808080, Mine2KBoard.CELL_TYPE_UNKNOWN);

		MAP_1_1 = new HashMap<Integer, Integer>();
		MAP_1_1.put(0xFFff0000, Mine2KBoard.CELL_TYPE_BURN);

		MAP_2_3 = new HashMap<Integer, Integer>();
		MAP_2_3.put(0xFFc0c0c0, Mine2KBoard.CELL_TYPE_BOMB);
		MAP_2_3.put(0xFFff0000, Mine2KBoard.CELL_TYPE_MISS);
	}

	private BufferedImage image;

	public void setImage(BufferedImage image) {
		this.image = image;
	}

	public int getCellType(int row, int column) {
		Integer value = null;

		int rgb = getRGB(3, 3, row, column);
		value = MAP_3_3.get(rgb);
		if (value != null) {
			return value;
		}

		rgb = getRGB(9, 11, row, column);
		value = MAP_9_11.get(rgb);
		if (value != null) {
			return value;
		}

		rgb = getRGB(8, 7, row, column);
		value = MAP_8_7.get(rgb);
		if (value != null) {
			return value;
		}

		rgb = getRGB(14, 8, row, column);
		value = MAP_14_8.get(rgb);
		if (value != null) {
			return value;
		}

		rgb = getRGB(1, 1, row, column);
		value = MAP_1_1.get(rgb);
		if (value != null) {
			return value;
		}

		rgb = getRGB(2, 3, row, column);
		value = MAP_2_3.get(rgb);
		if (value != null) {
			return value;
		}

		return Mine2KBoard.CELL_TYPE_UNDEFINED;
	}

	private int getRGB(int x, int y, int row, int column) {
		int offsetX = column * Mine2KBoard.CELL_SIZE;
		int offsetY = row * Mine2KBoard.CELL_SIZE;

		return image.getRGB(x + offsetX, y + offsetY);
	}

}
